package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @authar by xiecong
 * @Date 2022/3/9
 * @Description
 */
@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 点赞或取消点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDTO dto) {
        //1.注解校验参数，文章id和点赞方式(已写)
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "请先登陆");
        }
        //2.根据当前登录用户id查询行为实体对象
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(
                apUser.getId(), null);
        if (apBehaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "获取行为实体信息失败");
        }
        // 3. 如果是点赞操作,判断是否已经点赞
        Query query = Query.query(Criteria
                .where("entryId").is(apBehaviorEntry.getId())
                .and("articleId").is(dto.getArticleId()));
        ApLikesBehavior likesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);
        //3.1 如果已点赞，则不能重复点赞
        if (likesBehavior != null && dto.getOperation().intValue() == 0) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "不能重复点赞");
        }
        // 4. 如果没有点赞,向mongo点赞集合中添加点赞数据
        if (likesBehavior == null) {
            likesBehavior = new ApLikesBehavior();
            likesBehavior.setCreatedTime(new Date());
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setEntryId(apBehaviorEntry.getId());
            likesBehavior.setOperation((short)0);
            likesBehavior.setType((short)0);
            mongoTemplate.save(likesBehavior);
        } else {
            // 5. 如果是取消点赞操作  在mongo点赞集合中 删除对应点赞数据
            mongoTemplate.remove(query, ApLikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
